package com.smxy.mall.service.impl;

import com.smxy.mall.common.CustomException;
import com.smxy.mall.common.Response;
import com.smxy.mall.dao.NewsCatDao;
import com.smxy.mall.dao.NewsDao;
import com.smxy.mall.entity.News;
import com.smxy.mall.entity.NewsCat;
import com.smxy.mall.model.news.NewsCatRequest;
import com.smxy.mall.model.news.NewsRequest;
import com.smxy.mall.service.NewsService;
import com.smxy.mall.utils.Common;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class NewsServiceImpl implements NewsService {
    @Resource
    private NewsCatDao newsCatDao;
    @Resource
    private NewsDao newsDao;

    /**
     * 新增/编辑 分类
     * @param newsCatRequest
     * @return
     */
    @Override
    public NewsCat save(NewsCatRequest newsCatRequest) {
        NewsCat newsCat = new NewsCat();
        if(Common.isId(newsCatRequest.getId()+"")){

            newsCat.setId(newsCatRequest.getId());
        }
        newsCat.setCover(newsCatRequest.getCover());
        newsCat.setPid(newsCatRequest.getPid());
        newsCat.setName(newsCatRequest.getName());
        newsCat.setRemark(newsCatRequest.getRemark());
        return newsCatDao.save(newsCat);
    }

    /**
     * 分类列表
     * @param pid
     * @return
     */
    @Override
    public List<NewsCat> catList(Integer pid) {
        return newsCatDao.findByPid(pid);
    }

    /**
     * 新增/编辑 新闻
     * @param newsRequest
     * @return
     */
    @Override
    public News save(NewsRequest newsRequest) {
        News news = new News();
        if(Common.isId(newsRequest.getId()+"")){
            news.setId(newsRequest.getId());
        }
        news.setCategoryId(newsRequest.getCategoryId());
        news.setTitle(newsRequest.getTitle());
        news.setInfo(newsRequest.getInfo());
        news.setCover(newsRequest.getCover());
        news.setContent(newsRequest.getContent());
        return newsDao.save(news);
    }

    /**
     * 新闻详情
     * @param id 新闻id
     * @return
     */
    @Override
    public News detail(Integer id) {
        if(!Common.isId(id+"")){
            throw new CustomException(Response.fail("id无效"));
        }
        return newsDao.findById(id);
    }

    /**
     * 分类新闻列表
     * @param
     * @param pageable
     * @return
     */
    @Override
    public Page<News> newsList(Integer categoryId, Pageable pageable) {
//        return newsDao.findAll(example,pageable);
        return newsDao.findByCategoryId(categoryId,pageable);
    }

    /**
     * 全部新闻列表
     * @param pageable
     * @return
     */
    @Override
    public Page<News> newsList(Pageable pageable) {
        return newsDao.findAll(pageable);
    }
}
